﻿using System.Net.NetworkInformation;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ServiceApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string PipeName = "MyAppPipe";
        private NamedPipeService? _pipeService;

        public MainWindow()
        {
            InitializeComponent();
            InitializePipeService();
        }

        private void InitializePipeService()
        {
            _pipeService = new NamedPipeService(PipeName);
            _pipeService.Connected += PipeService_Connected;
            _pipeService.Disconnected += PipeService_Disconnected;
            _pipeService.MessageReceived += PipeService_MessageReceived;
            _pipeService.ErrorOccurred += PipeService_ErrorOccurred;
        }

        private async void btnStart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await _pipeService!.StartAsync();
                tbStatus.Text = "运行中...";
                btnStart.IsEnabled = false;
                btnStop.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"启动失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            _pipeService?.Dispose();
            tbStatus.Text = "已停止";
            btnStart.IsEnabled = true;
            btnStop.IsEnabled = false;

            // 重新初始化服务以便再次启动
            InitializePipeService();
        }

        private async void btnSend_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtMessage.Text))
            {
                MessageBox.Show("请输入消息内容", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            try
            {
                await _pipeService!.SendMessageAsync(txtMessage.Text);
                lbMessages.Items.Add($"发送: {txtMessage.Text}");
                txtMessage.Text = "";
            }
            catch (Exception ex)
            {
                lbMessages.Items.Add($"发送失败: {ex.Message}");
            }
        }

        private void PipeService_Connected(object sender, EventArgs e)
        {
            Dispatcher.Invoke(() => lbMessages.Items.Add("客户端已连接"));
        }

        private void PipeService_Disconnected(object sender, EventArgs e)
        {
            Dispatcher.Invoke(() =>
            {
                lbMessages.Items.Add("客户端已断开");
                // 自动重置服务状态
                if (btnStop.IsEnabled)
                {
                    btnStop_Click(null, EventArgs.Empty);
                }
            });
        }

        private void PipeService_MessageReceived(object sender, string message)
        {
            Dispatcher.Invoke(() => lbMessages.Items.Add($"接收: {message}"));
        }

        private void PipeService_ErrorOccurred(object sender, Exception e)
        {
            Dispatcher.Invoke(() =>
            {
                lbMessages.Items.Add($"错误: {e.Message}");
                // 发生错误时自动停止服务
                if (btnStop.IsEnabled)
                {
                    btnStop_Click(null, EventArgs.Empty);
                }
            });
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            _pipeService?.Dispose();
        }
    }
}